define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

	var getFxBuildingsController = function(){
		return getServer() + "/fxBuildingss";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
		var t = setInterval(function () {
			if (T.MarkerClusterer) {
				clearInterval(t);
				initSearchBlock();
				queryBtnBind();
				initcreateProvince();
				initYearDate();
				initStructureTypeSelect();
				initMap();
			}
		}, 10);
	};
	var initcreateProvince = function () {
		var html = "";
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer()+"/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer()+"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer()+"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	};
	var initYearDate = function() {
		$("#yearCondition").datetimepicker({
			//设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
			language : "cn",
			//输出格式化
			format : 'yyyy-mm-dd',
			//直接选择‘今天’
			todayBtn : true,
			//设置最精确的时间选择视图
			minView : 'month',
			//高亮当天日期
			todayHighlight : true,
			//选择完毕后自动关闭
			autoclose : true
		});
	};
	var initStructureTypeSelect = function () {
		$.ajax({
			url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "structureType",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("structureTypeSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
			queryFxBuildingsData();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
	            $("#citySelect").val("");
	            $("#areaSelect").val("");
				$("#yearCondition").val("");
				$("#buildingNameCondition").val("");
	            $("#structureTypeSelect").val("");
			});
        $("#fx-Building-Map-Grid-Close").click(function () {
        	$("#fx-buildings-attributes").hide();
		});
	};
	var queryFxBuildingsData = function(zoomType) {
        //$("#fxBuildingsGrid").html("Map");
        console.log("####queryFxBuildingsData####");
		console.log($("#provinceSelect").val());
		var bounds = tdMap.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), zoom = tdMap.getZoom();
		var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "",
			year = $("#yearCondition").val() || "", buildingName = $("#buildingNameCondition").val() || "", structureType = $("#structureTypeSelect").val() || "";
		//console.log(getFxBuildingsController() + "/getFxBuildingss?province=" + province + "&city=" + city + "&area=" + area + "&year=" + year + "&buildingName=" + buildingName + "&structureType=" + structureType);
		var formData = {province: province, city: city, area: area,
						year: year, buildingName: buildingName, structureType: structureType,
						bounds: sw.lng + " " + sw.lat + "," + ne.lng + " " + ne.lat, zoom: zoom};
		loading.show();
		$.ajax({
			url: getFxBuildingsController() + "/searchFxBuildings",
			data: formData,
			type: "POST",
			success: function (data) {
				loading.close();
				console.log(data);
				addMarkersToMap(data, zoomType);
			},
			error: function(xhr, state, errorThrown){
				loading.close();
				Util.alert("查询数据出现异常!");
			}
		});
    };

	var loading = Loading({text : "正在查询数据..."});
	var tdMap, global_markerClusterer, global_overlays = [];
	var initMap = function () {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 20;
		$("#fx-buildings-data-mapDiv").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('fx-buildings-data-mapDiv', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

		$("#fx-buildings-attributes").children().eq(0).click(function(){
			$("#fx-buildings-attributes").css("display", "none");
		});

		tdMap.addEventListener("click", function (e) {
			$('#queryDiv').hide(200);
		});
		tdMap.addEventListener("zoomstart", function (e) {
			console.log(e);
			//clearMarkers();
		});
		var isZoomendTo = false;
		tdMap.addEventListener("zoomend", function (e) {
			isZoomendTo = true;
			console.log(e);
			queryFxBuildingsData("zoomend");
		});

		tdMap.addEventListener("movestart", function (e) {
			//console.log("movestart");
			//clearMarkers();
		});
		tdMap.addEventListener("moveend", function (e) {
			if (isZoomendTo) {
				isZoomendTo = false;
				return;
			}
			console.log(e);
			queryFxBuildingsData("moveend");
		});

	};
	var addMarkersToMap = function (result, zoomType) {
		tdMap.clearOverLays();
		var data = result.data, res_zoom = result ? result.zoom : 0;
		if (data && data.length) {
			var markers = [], points = [];
			for (var i = 0;i < data.length;i++) {
				if (!data[i].lon || !data[i].lat) continue;
				var point = new T.LngLat(data[i].lon, data[i].lat);
				/*
				//方法【1】的步骤1-1
				var icon = new T.Icon({
					iconUrl: "/fxpg/static/app/fxpg/fx_plugins/images/marker-red.png",
					iconSize: new T.Point(20, 20),
					iconAnchor: new T.Point(-10, -10)
				});
				var marker = new T.Marker(point, {icon: icon, _data: data[i]});
				marker.addEventListener("click", buildingMarkerClick);
				//tdMap.addOverLay(marker);
				markers.push(marker);*/

				//方法【2】的步骤2-1
				point._data = data[i];
				if (res_zoom < 15) {
					var options = getOverlayOptions(data[i].extend1);
					var overlay = new DefinedOverlay(point, data[i].extend1, options);
					tdMap.addOverLay(overlay);
					global_overlays.push(overlay);
				}

				points.push(point);
			}
			//方法【1】的步骤1-2
			//tdMap.setViewport(points);
			//global_markerClusterer = new T.MarkerClusterer(tdMap, {markers: markers, girdSize: 80, styles: markerClustererStyles});

			//方法【2】的步骤2-2
			if (res_zoom >= 15) addCloudCollection(points, zoomType);
		} else {
			//Util.alert("查询无数据!");
		}
	};
	var removeMarkerClick = function (marker) {
		marker.removeEventListener("click", buildingMarkerClick);
	};
	var buildingMarkerClick = function (e) {
		//alert(e.lnglat.getLng() + "," + e.lnglat.getLat());
		//console.log(e);
		console.log(this.options._data);
		var _data = this.options._data;
		$("#fx-buildings-attributes").css("display", "block");
		var divStr = "<table class='table-bordered table-hover table-building' style='width: 100%;height: 100%;'>" +
						"<tbody>" +
							"<tr>" +
								"<td>省</td>" +
								"<td>" + _data.province + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>市</td>" +
								"<td>" + _data.city + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>区（县）</td>" +
								"<td>" + (_data.area ? _data.area : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>建筑物名称</td>" +
								"<td>" + (_data.buildingName ? _data.buildingName : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>结构类型</td>" +
								"<td>" + (_data.structureType ? _data.structureType : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>建筑面积</td>" +
								"<td>" + (_data.buildingArea ? _data.buildingArea : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>人数</td>" +
								"<td>" + (_data.peopleNumber ? _data.peopleNumber : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>用途</td>" +
								"<td>" + (_data.purpose ? _data.purpose : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>层数</td>" +
								"<td>" + (_data.floorNumber ? _data.floorNumber : "") + "</td>" +
							"</tr>" +
							"<tr>" +
								"<td>年代</td>" +
								"<td>" + (_data.year ? _data.year : "") + "</td>" +
							"</tr>" +"<tr>" +
								"<td>现设防烈度</td>" +
								"<td>" + (_data.currentIntensity ? _data.currentIntensity : "") + "</td>" +
							"</tr>" +
						"</tbody>" +
					"</table>";
		$("#fx-buildings-attributes").children().eq(1).html(divStr);
	};

	var markerClustererStyles = [
		{
			url:'/fxpg/static/app/fxpg/fx_plugins/images/cluster0.png',
			size:[53, 52], //图片大小
			//offset:new T.Point(-15, -13), //显示图片的偏移量
			textColor:'#000000', //显示数字的颜色
			//textSize:8,//显示文字的大小
			range:[0, 50],
		},
		{
			url:'/fxpg/static/app/fxpg/fx_plugins/images/cluster1.png',
			size:[53, 52],
			//offset:new T.Point(-20, -17),
			textColor:'#000000',
			//textSize:10,
			range:[50, 200],
		},
		{
			url:'/fxpg/static/app/fxpg/fx_plugins/images/cluster2.png',
			size:[53, 52],
			//soffset:new T.Point(-10, -22),
			textColor:'#000000',
			//textSize:12,
			range:[200, 500],
		},
		{
			url:'/fxpg/static/app/fxpg/fx_plugins/images/cluster3.png',
			size:[53, 52],
			//soffset:new T.Point(-10, -22),
			textColor:'#000000',
			//textSize:12,
			range:[500, 1000],
		},
		{
			url:'/fxpg/static/app/fxpg/fx_plugins/images/cluster4.png',
			size:[53, 52],
			//soffset:new T.Point(-10, -22),
			textColor:'#000000',
			//textSize:12,
			range:[1000, 10000],
		}
	];
	var collection, current_points = [];
	var addCloudCollection = function (lnglats, zoomType) {
		if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
			if (collection) {
				collection.clear();
				if (tdMap.getZoom() >= 15 && zoomType == "moveend") {
					current_points = filterPointsIsInBounds(lnglats, current_points);
				} else {
					current_points = lnglats;
				}
				collection.setLnglats(current_points);
			} else {
				current_points = lnglats;
				collection = new T.CloudMarkerCollection(current_points, {
					color: 'blue',
					SizeType: TDT_POINT_SIZE_NORMAL
				});
				tdMap.addOverLay(collection);
				collection.addEventListener("click", pointClick);
			}
		} else {
			alert('此功能目前只兼容chrome、safari、IE9及以上浏览器');
		}
	}
	var filterPointsIsInBounds = function (lnglats, points) {
		var isInMap = false, i, len_i, j, len_j, temp_arr = [];
		for (i = 0, len_i = lnglats.length; i < len_i; i++) {
			isInMap = false;
			for (j = 0, len_j = points.length; j < len_j; j++) {
				if (lnglats[i]._data.uuid == points[j]._data.uuid) {
					isInMap = true;
					break;
				}
			}
			if (!isInMap) temp_arr.push(lnglats[i]);
		}
		points = points.concat(temp_arr);

		var bounds = tdMap.getBounds();
		for (let i = 0; i < points.length; i++) {
			if (!(bounds.contains(points[i]))) {
				points.splice(i, 1);
				i--;
			}
		}
		return points;
	}
	var DefinedOverlay = T.Overlay.extend({
		initialize: function (lnglat, text, options) {
			this.lnglat = lnglat;
			this.setOptions(options);
			this._text = text;
		},
		onAdd: function (map) {
			this.map = map;
			var div = this._div = document.createElement("div");
			div.style.position = "absolute";
			div.style.width = this.options.size[0] + "px";
			div.style.height = this.options.size[1] + "px";
			div.style.lineHeight = this.options.size[1] + "px";
			div.style.backgroundImage = "url(" + this.options.url + ")";
			div.style.fontSize = "10pt";
			div.style.backgroundSize = "52px 51px";
			div.style.color = this.options.textColor;
			div.style.fontWeight = "700";
			div.style.textAlign = "center";
			div.style.backgroundRepeat = "no-repeat";
			//div.style.backgroundPosition = "-5px";
			div.style.cursor = "pointer";

			var span = document.createElement("span");
			span.appendChild(document.createTextNode(this._text));
			div.appendChild(span);

			map.getPanes().overlayPane.appendChild(this._div);
			this.update(this.lnglat);
		},
		onRemove: function () {
			var parent = this._div.parentNode;
			if (parent) {
				parent.removeChild(this._div);
				this.map = null;
				this._div = null;
			}
		},
		update: function () {
			var pos = this.map.lngLatToLayerPoint(this.lnglat);
			this._div.style.top = ( pos.y - 36) + "px";
			this._div.style.left = (pos.x - 11) + "px";
		}
	});
	var getOverlayOptions = function (num) {
		var option = {};
		if (num >= 0 && num < 80) {
			option = markerClustererStyles[0];
		} else if (num >= 80 && num < 200) {
			option = markerClustererStyles[1];
		} else if (num >= 200 && num < 500) {
			option = markerClustererStyles[2];
		} else if (num >= 500 && num < 1000) {
			option = markerClustererStyles[3];
		} else if (num >= 1000 && num < 100000) {
			option = markerClustererStyles[4];
		} else if (num >= 100000) {
			option = markerClustererStyles[4];
		}
		return option;
	};
	var pointClick = function (e) {
		//alert(e.lnglat.getLng() + "," + e.lnglat.getLat());
		//console.log(e);
		//console.log(this.options._data);
		var _data = (e.lnglat && e.lnglat._data) ? e.lnglat._data : this.options._data;
		$("#fx-buildings-attributes").css("display", "block");
		var divStr = "<table class='table-bordered table-hover table-building' style='width: 100%;height: 100%;'>" +
			"<tbody>" +
			"<tr>" +
			"<td>省</td>" +
			"<td>" + _data.province + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>市</td>" +
			"<td>" + _data.city + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>区（县）</td>" +
			"<td>" + (_data.area ? _data.area : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>建筑物名称</td>" +
			"<td>" + (_data.buildingName ? _data.buildingName : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>结构类型</td>" +
			"<td>" + (_data.structureType ? _data.structureType : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>建筑面积</td>" +
			"<td>" + (_data.buildingArea ? _data.buildingArea : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>人数</td>" +
			"<td>" + (_data.peopleNumber ? _data.peopleNumber : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>用途</td>" +
			"<td>" + (_data.purpose ? _data.purpose : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>层数</td>" +
			"<td>" + (_data.floorNumber ? _data.floorNumber : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>年代</td>" +
			"<td>" + (_data.year ? _data.year : "") + "</td>" +
			"</tr>" +"<tr>" +
			"<td>现设防烈度</td>" +
			"<td>" + (_data.currentIntensity ? _data.currentIntensity : "") + "</td>" +
			"</tr>" +
			"</tbody>" +
			"</table>";
		$("#fx-buildings-attributes").children().eq(1).html(divStr);
	};


	return {
		init:init
	};
});
